<template>
	<div ref="boxRef" v-if="visible" class="task-list-bar" :style="positionStyle">
		<header class="queue-header">
			<h3>任务队列</h3>
			<div class="clear-operation" @click="handelClear">
				<global-svg-icon icon-name="brush-2-line" width="14px" height="14px"></global-svg-icon>
				<div style="margin-left: 4px">清空</div>
			</div>
		</header>
		<main class="queue-main">
			<div v-if="taskStore.taskDataList?.length === 0" style="display: flex; justify-content: center; padding-top: 160px">
				<global-svg-icon icon-name="empty" width="200px" height="72px" style="color: #4e596a"></global-svg-icon>
			</div>
			<div :key="item.id" v-for="item in taskStore.taskDataList" class="queue-item">
				<div class="the-queue">
					<div class="item_left">
						<i class="iconfont icon-file-line"></i>
						<div class="the-queue-name" :title="item?.name">{{ item?.name }}</div>
					</div>
					<div class="item_right">
						<p v-if="item.jobStates === 1">资源准备中..</p>
						<p v-else-if="item.jobStates === 2">排队中..</p>
						<a-button v-else :disabled="item?.downloaddisabled" class="operation-buttons" @click="handleDownloadRetry(item)">{{
							item.jobStates === 1 ? '' : item.jobStates === -1 ? '重试' : '下载'
						}}</a-button>
					</div>
					<i class="iconfont icon-close-line" @click="handleDelete(item)"> </i>
				</div>
			</div>
		</main>
	</div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch, onBeforeUnmount } from 'vue';
import { commonTaskApi } from '../../../api';
import { useTaskStore } from '@/global-store/task';
import { useDeleteModal } from '@/global-hooks/base.hooks';

interface TsProps {
	buttonId: string;
	visible: boolean;
	taskNum: number;
}

interface taskType {
	name: string;
	id: string;
	jobStates: number;
}

const props = withDefaults(defineProps<TsProps>(), {
	visible: false,
	taskNum: 0,
	buttonId: 'taskBtnID'
});

const emits = defineEmits(['update:taskNum', 'update:visible']);

const positionStyle = ref({ '--top-fixed': '10px', '--left-fixed': '20px' });
const { setOpenDeleteModal } = useDeleteModal();
const taskStore = useTaskStore();
const $message: any = inject('$message');

// 清空
const handelClear = () => {
	const clearModalInfo = { title: '确定清空当前任务队列？', okText: '删除', cancelText: '取消' };
	const clearFun = async (): Promise<void> => {
		try {
			// let id = taskStore.taskDataList?.map((i: any) => i.id).toLocaleString();
			let res: any = await commonTaskApi.deleteExport({ pageType: 1 });
			if (res.code === 0) {
				$message.success('删除成功');
				await taskStore.getTaskList();
			}
		} catch (error) {
			console.log(error);
		}
	};
	setOpenDeleteModal(clearFun, clearModalInfo);
};

// 删除
const handleDelete = async (item: any) => {
	let index = taskStore.taskDataList.findIndex((i: any) => {
		if (i.id === item.id) {
			return true;
		}
	});
	const clearModalInfo = { title: '删除后不可恢复，是否确认删除！', okText: '删除', cancelText: '取消' };
	const deleteFun = async (): Promise<void> => {
		try {
			let params = {
				idList: [item.id],
				pageType: 1
			};
			let res: any = await commonTaskApi.deleteExport(params);
			if (res.code === 0) {
				taskStore.taskDataList.splice(index, 1);
				await taskStore.getTaskList();
				$message.success('删除成功');
			}
		} catch (error) {
			console.log(error);
		}
	};
	setOpenDeleteModal(deleteFun, clearModalInfo);
};

//
//下载或重试操作
const handleDownloadRetry = async (item: any) => {
	item.downloaddisabled = true;

	if (item.jobStates === 0) {
		try {
			$message.info('正在导出，请稍后...');
			const res: TsRes = await commonTaskApi.getdownloadByPreSignature({ id: item.id, pageType: 1 });
			if (res.code === 0) {
				item.downloaddisabled = false;
			}
			const a = document.createElement('a');
			a.style.display = 'none';
			a.href = res.data || '';
			a.click(); //触发下载
			URL.revokeObjectURL(a.href); //释放URL对象
		} catch (error) {
			console.log(error);
		}
	} else if (item.jobStates === -1) {
		const res: TsRes = await commonTaskApi.exportPrepare({ exportId: item.id, retryMark: 1, pageType: 1 });
		if (res.code === 0) {
			item.downloaddisabled = false;
		}
		taskStore.getTaskList();
	}
};

// 点击其他区域关闭盒子
const boxRef = ref<HTMLElement>();
const handleClickOutside = (event: { target: any }) => {
	// 不是 点击任务确认弹窗、点击打开弹窗的按钮
	if (
		boxRef.value &&
		!boxRef.value.contains(event.target) &&
		!document.getElementById(props.buttonId)?.contains(event.target) &&
		!document.getElementsByClassName('ant-modal-wrap').length
	) {
		return emits('update:visible', false);
	}
};

// 页面尺寸改变更新盒子位置
const handleResize = () => {
	let btnDom = document.getElementById(props.buttonId);
	const rect = btnDom?.getBoundingClientRect();
	positionStyle.value = {
		'--top-fixed': `${rect?.bottom}px`,
		'--left-fixed': `${rect?.right}px`
	};
};

// 监听弹窗打开时候点击事件
const stopWatching = watch(
	() => props.visible,
	() => {
		if (props.visible) {
			handleResize();
			window.addEventListener('resize', handleResize);
			document.addEventListener('click', handleClickOutside);
			return;
		}
		window.removeEventListener('resize', handleResize);
		document.removeEventListener('click', handleClickOutside);
	},
	{ deep: true }
);

onMounted(() => {
	handleResize();
});
onBeforeUnmount(() => {
	stopWatching();
});
</script>

<style lang="less" scoped>
.task-list-bar {
	position: fixed;
	top: calc(5px + var(--top-fixed));
	left: var(--left-fixed);
	z-index: 199999;
	overflow: hidden;
	width: 320px;
	height: 560px;
	border: 1px solid @borderColor03;
	border-radius: 8px;
	background: rgba(14, 22, 36, 0.9);
	box-shadow:
		0 12px 30px 0 rgba(0, 0, 0, 0.3),
		0 0 12px 0 rgba(0, 0, 0, 0.15);
	transform: translate(calc(-100% + 16px), 0);

	.queue-header {
		box-sizing: border-box;
		display: flex;
		height: 46px;
		align-items: center;
		padding: 12px 16px;
		line-height: 32px;
		background: #1a212f;
		justify-content: space-between;

		> h3 {
			font-size: 14px;
			font-weight: 700;
			color: @text01;
		}

		.clear-operation {
			display: flex;
			font-size: 14px;
			font-weight: 400;
			font-style: normal;
			text-align: center;
			color: @text03;
			cursor: pointer;
			align-items: center;

			> i {
				margin-right: 4px;
			}
		}
	}

	.queue-main {
		box-sizing: border-box;
		overflow-y: auto;
		// background: #202c40;
		width: 100%;
		height: calc(560px - 46px);
		padding: 16px;

		.queue-item {
			box-sizing: border-box;
			position: relative;
			display: flex;
			height: 46px;
			margin-bottom: 16px;
			padding: 12px 24px 12px 8px;
			align-items: center;

			&:hover {
				border-radius: 6px;
				background: @mask01;

				.icon-close-line {
					display: block;
					transition: 0.3s all;
					cursor: pointer;
				}
			}

			&:not(:last-child) {
				&::after {
					position: absolute;
					right: 0;
					bottom: -8px;
					width: 100%;
					height: 1px;
					background-color: @borderColor03;
					content: '';
				}
			}

			.the-queue {
				display: flex;
				align-items: center;
				justify-content: space-between;
				width: 100%;

				.item_left {
					display: flex;
					align-items: center;
					overflow: hidden; //超出部分隐藏
					white-space: nowrap; //不换行
					text-overflow: ellipsis; //文本溢出显示省略号
					.icon-file-line {
						margin-right: 4px;
						font-size: 22px;
						color: @text04;
					}

					.the-queue-name {
						overflow: hidden;
						max-width: 120px;
						font-family: 'Noto Sans SC';
						font-size: 14px;
						white-space: nowrap;
						text-overflow: ellipsis;
						color: #f0f6fc;
						cursor: default;
						flex: 1;
					}
				}

				.item_right {
					display: flex;
					// width: 33%;
					align-items: center;

					> p {
						font-size: 12px;
						line-height: 20px;
						color: @text03;
					}

					.operation-buttons {
						box-sizing: border-box;
						width: 56px !important;
						height: 30px !important;
						border: 1px solid #2b3a50;
						border-radius: 6px;
						padding: 4px 12px;
						font-size: 14px;
						font-weight: 400;
						text-align: center;
						color: @text01;

						/* Shadow/button */
						box-shadow: 0 2px 0 0 rgba(0, 0, 0, 0.04);
					}
				}
			}

			.icon-close-line {
				position: absolute;
				right: 4px;
				display: none;
				color: @text03;
			}
		}

		.operation {
			display: flex;
			justify-content: space-between;
			align-items: center;

			> div {
				display: flex;
				align-items: center;

				> .iconfont {
					margin-top: 2px;
					margin-right: 4px;
					font-size: 14px;
				}
			}
		}
	}

	.queue-footer {
		height: 32px;
		background: #1a212f;

		.footer-prompt {
			padding: 0 16px;
			font-family: 'Noto Sans SC';
			font-size: 12px;
			line-height: 32px;
			color: @text03;
			cursor: default;
		}
	}
}
</style>
